package com.hongdee.scm.stock.service.impl;

import com.hongdee.common.util.TokenUtil;
import com.hongdee.scm.common.service.impl.Common;
import com.hongdee.scm.enterwarehouse.entity.TScmEnterWareHouse;
import com.hongdee.scm.monthlybalance.service.ITScmMonthlyBalanceService;
import com.hongdee.scm.stock.dao.ITScmStockDao;
import com.hongdee.scm.stock.entity.TScmStock;
import com.hongdee.scm.stock.service.ITScmStockService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 名  称:TScmStockServiceImpl
 * 类  型:class
 * 描  述:
 * 路  径:com.hongdee.scm.stock.service.impl
 * 作  者: 术洪超
 * 日  期:2017-05-12 14:03
 */
@Service
public class TScmStockServiceImpl implements ITScmStockService {

    String tabName = "T_SCM_STOCK";
    String entityName = "TScmStock";

    private String tabName1 = "T_SCM_CAR";
    //车型对照表
    private String tabCarModel = " t_bc_carmodel";
    //配置对照表
    private String tabCarConfig = "t_bc_carconfigure";

    @Autowired
    private ITScmStockDao itScmStockDao;
    @Autowired
    private ITScmMonthlyBalanceService itScmMonthlyBalanceService;


    /**
     * @param data 要保存的实体
     * @return Map
     * @throws Exception
     * @desc 车辆入库，保存添加或者修改的实体内容，通过主键判断
     * @author 术洪超
     */
    @Override
    public void save(Map data, String uid, String type) throws Exception {

        //validate_status
        if (data.size() > 0) {
            TScmStock entity = new TScmStock();
            entity.setCreateUser(uid);
            entity.setCreateTime(Calendar.getInstance().getTimeInMillis());
            entity.setCompanyId(TokenUtil.getCompanyId(uid));
            entity.setAllocationStatus("0");

            TScmEnterWareHouse inRecord = new TScmEnterWareHouse();
            inRecord.setCreateUser(uid);
            inRecord.setCreateTime(Calendar.getInstance().getTimeInMillis());
            inRecord.setCompanyId(TokenUtil.getCompanyId(uid));

            if (type.equals("0")) {
                //本店新增入库

                Map map = (Map) data.get("addFormData");
                if (map.size() > 0) {

                    if (map.get("warehouseId") != null && !StringUtils.isEmpty(map.get("warehouseId"))) {
                        entity.setWarehouseId(map.get("warehouseId").toString());
                        inRecord.setWarehouseId(map.get("warehouseId").toString());
                    }
                    if (map.get("enterDate") != null && !StringUtils.isEmpty(map.get("enterDate"))) {
                        //确认入库时间不能大于系统时间
                        int result = map.get("enterDate").toString().compareTo(new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
                        if(result > 0 ){
                            throw new Exception("确认入库时间不能大于系统时间");
                        }
                        if(this.itScmMonthlyBalanceService.ifMonthlyBalance(TokenUtil.getCompanyId(uid),new SimpleDateFormat("yyyy-MM-dd").parse(map.get("enterDate").toString()))){
                            Calendar lastDate = Calendar.getInstance();
                            lastDate.setTime(new SimpleDateFormat("yyyy-MM-dd").parse(map.get("enterDate").toString()));
                            lastDate.set(Calendar.DATE, 1);
                            lastDate.add(Calendar.MONTH, 1);
                            lastDate.add(Calendar.DATE, -1);
                            String format = new SimpleDateFormat("yyyy-MM-dd").format(lastDate.getTime());
                            throw new Exception("已月结或月结中,不能车辆入库,请输入"+format+"之后的日期");
                        }
                        entity.setEnterDate(map.get("enterDate").toString());
                        inRecord.setEnterDate(map.get("enterDate").toString());
                    }

                }

                List<Map> list = (List<Map>) data.get("multipleSelectionCar");

                if (list.size() > 0) {
                    for (Map mapCar : list) {

                        if (checkCarInStock(mapCar.get("id").toString()))
                        {
                            continue;
                        }
                        if (mapCar.get("vin") == null || StringUtils.isEmpty(mapCar.get("vin"))) {
                            continue;
                        }
                        entity.setId(null);
                        inRecord.setId(null);

                        entity.setCarId(mapCar.get("id").toString());
                        entity.setVin(mapCar.get("vin").toString());

                        inRecord.setCarId(mapCar.get("id").toString());
                        inRecord.setVin(mapCar.get("vin").toString());
                        if (mapCar.get("carSeriesId") != null && !StringUtils.isEmpty(mapCar.get("carSeriesId"))) {
                            //判断该车的车系是否已维护
                            if(this.itScmStockDao.info("select * from t_bc_car_series where id = ? and res_status = '1'",mapCar.get("carSeriesId")).size()>0){
                                entity.setCarSeries(mapCar.get("carSeriesId").toString());
                            }else{
                                throw new Exception(mapCar.get("vin")+"该车辆的车系不存在!");
                            }
                        }
                        if (mapCar.get("carModelId") != null && !StringUtils.isEmpty(mapCar.get("carModelId"))) {
                            //判断该车的车型是否已维护
                            if(this.itScmStockDao.info("select * from t_bc_carmodel where id = ? and res_status = '1'",mapCar.get("carModelId")).size()>0){
                                entity.setCarModel(mapCar.get("carModelId").toString());
                            }else{
                                throw new Exception(mapCar.get("vin")+"该车辆的车型不存在!");
                            }
                        }
                        if (mapCar.get("configureId") != null && !StringUtils.isEmpty(mapCar.get("configureId"))) {
                            //判断该车的配置是否已维护
                            if(this.itScmStockDao.info("select * from t_bc_carconfigure where id = ? and res_status = '1'",mapCar.get("configureId")).size()>0){
                                entity.setConfigureName(mapCar.get("configureId").toString());
                            }else{
                                throw new Exception(mapCar.get("vin")+"该车辆的配置不存在!");
                            }
                        }
                        if (mapCar.get("brand") != null && !StringUtils.isEmpty(mapCar.get("brand"))) {
                            entity.setBrand(mapCar.get("brand").toString());
                        }
                        if (mapCar.get("engineNum") != null && !StringUtils.isEmpty(mapCar.get("engineNum"))) {
                            entity.setEngineNum(mapCar.get("engineNum").toString());
                        }
                        if (mapCar.get("appearanceName") != null && !StringUtils.isEmpty(mapCar.get("appearanceName"))) {
                            entity.setAppearanceName(mapCar.get("appearanceName").toString());
                        }
                        /*  if (mapCar.get("appearanceId") != null && !StringUtils.isEmpty(mapCar.get("appearanceId"))) {
                            entity.setAppearanceId(mapCar.get("appearanceId").toString());
                        }*/
                        if (mapCar.get("status") != null && !StringUtils.isEmpty(mapCar.get("status"))) {
                            //enter_type入库类型（1采购入库2已售3调拨入库）
                            //车辆状态为采购在途，入库类型为采购入库
                            if (mapCar.get("status").toString().equals("0")) {
                                entity.setEnterType("1");
                            }
                            //车辆状态为调拨在途，入库类型为采调拨入库
                            if (mapCar.get("status").toString().equals("3")) {
                                entity.setEnterType("3");
                            }
                            //车辆状态为已售，入库类型为退车回库
                            if (mapCar.get("status").toString().equals("2")) {
                                entity.setEnterType("2");
                            }
                        }

                        entity.setAllocationStatus("0");
                        inRecord.setEnterType(entity.getEnterType());

                        //entity.setSaleType("1");

                        this.itScmStockDao.saveOrUpdate(entity);
                        this.itScmStockDao.saveOrUpdate(inRecord);
                        //更新车辆表里的车辆状态和财务状态
                        //更新车辆状态位在库
                        this.updateCarStatus(mapCar.get("id").toString());
                        //销售出去的车辆重新购买回库
                        if(this.itScmStockDao.list("select * from t_scm_sale_order_detail where vin=? and status = '0' and company_id=?",entity.getVin(),TokenUtil.getCompanyId(uid)).size()>0){
                            //获取这个vin车辆第一次入库时的初次入库时间
                            List l = this.itScmStockDao.list("select * from t_scm_car where vin=? and company_id = ? order by create_time asc limit 1",entity.getVin(),TokenUtil.getCompanyId(uid));
                            String enterDateStart = ((Map)l.get(0)).get("enterWarehouseDateStart").toString();
                            this.itScmStockDao.executeSQL("update t_scm_car set enter_warehouse_date_start = ? where id=? and enter_warehouse_date_start is null and finance_type ='1' ",enterDateStart,entity.getCarId());
                        }else{//正常车辆入库
                            this.itScmStockDao.executeSQL("update t_scm_car set enter_warehouse_date_start = ? where id=? and enter_warehouse_date_start is null and finance_type ='1' ",entity.getEnterDate(),entity.getCarId());
                        }
                    }

                }
            }
            //非本店新增入库

//            if (type.equals("1")) {
//
//                Map mapNos = (Map) data.get("addNoStoreFormDatas");
//                if (mapNos.size() > 0) {
//
//                    if (mapNos.get("vin") != null && !mapNos.get("vin").toString().equals("")) {
//                        entity.setVin(mapNos.get("vin").toString());
//                    }
//                    if (mapNos.get("warehouseId") != null && !mapNos.get("warehouseId").toString().equals("")) {
//                        entity.setWarehouseId(mapNos.get("warehouseId").toString());
//                    }
//                    if (mapNos.get("enterDate") != null && !mapNos.get("enterDate").toString().equals("")) {
//                        entity.setEnterDate(mapNos.get("enterDate").toString());
//                    }
//                }
//            }


            this.itScmStockDao.saveOrUpdate(entity);
        } else {
            throw new Exception("请选择车辆！");
        }
    }

    /**
     * @param uid   登录用户 ID
     * @param start 起始记录
     * @param limit 页面大小
     * @param data  参数数组
     * @return Map
     * @throws Exception
     * @desc 通过 JDBCDao分页查询
     * @author 术洪超
     */
    @Override
    public Map page(String start, String limit, Map data, String uid) throws Exception {

        List params = new ArrayList();
        String sql = "select c.*,m.model_name,w.warehouse_name,c.certificate_num, cc.configure_name,c.color_name,c.trim_name from " +
                tabName + " s left join t_scm_warehouse w on s.warehouse_id = w.id left join t_scm_car c on c.vin = s.vin left join " +
                " t_bc_carconfigure cc on cc.id = c.configure_id left join t_bc_carmodel m on m.id = s.car_model   where s.company_id = ? ";

        params.add(TokenUtil.getCompanyId(uid));

        if (data.get("startDate") != null && !StringUtils.isEmpty(data.get("stopDate"))) {
            sql += "and s.enterDate between ? and ? ";
            params.add(data.get("startDate"));
            params.add(data.get("stopDate"));
        }

        if (data.get("carModel") != null && !StringUtils.isEmpty(data.get("carModel"))) {
            sql += "and s.car_model = ?";
            params.add(data.get("carModel"));
        }

        if (data.get("enterWarehouseType") != null && !StringUtils.isEmpty(data.get("enterWarehouseType"))) {
            sql += "and s.enter_type = ?";
            params.add(data.get("enterWarehouseType"));
        }

        if (data.get("enterWarehouseAge") != null && !StringUtils.isEmpty(data.get("enterWarehouseAge"))) {

            switch (data.get("enterWarehouseAge").toString()) {
                //入库一个月以内
                case "0": {
                    sql += " and TIMESTAMPDIFF(MONTH,s.enter_date,DATE_FORMAT(NOW(),'%Y-%m-%d')) <1";
                }
                break;
                //入库一到三个月
                case "1": {
                    sql += " and 1<= TIMESTAMPDIFF(MONTH,s.enter_date,DATE_FORMAT(NOW(),'%Y-%m-%d')) and TIMESTAMPDIFF(MONTH,s.enter_date,DATE_FORMAT(NOW(),'%Y-%m-%d')) < 3";
                }
                break;
                //入库三到六个月
                case "2": {
                    sql += " and 3<= TIMESTAMPDIFF(MONTH,s.enter_date,DATE_FORMAT(NOW(),'%Y-%m-%d')) and TIMESTAMPDIFF(MONTH,s.enter_date,DATE_FORMAT(NOW(),'%Y-%m-%d'))<6";
                }
                break;
                //入库六到十二个月
                case "3": {
                    sql += " and 6<= TIMESTAMPDIFF(MONTH,s.enter_date,DATE_FORMAT(NOW(),'%Y-%m-%d')) and TIMESTAMPDIFF(MONTH,s.enter_date,DATE_FORMAT(NOW(),'%Y-%m-%d'))<12";
                }
                break;
                //入库十二个月以上
                case "4": {
                    sql += " and TIMESTAMPDIFF(MONTH,s.enter_date,DATE_FORMAT(NOW(),'%Y-%m-%d'))>12";
                }
                break;
            }

        }

        if (data.get("inventoryId") != null && !StringUtils.isEmpty(data.get("inventoryId"))) {
            sql += " and s.inventory_id = ?";
            params.add(data.get("inventoryId"));
        }
        sql += " order by s.create_time desc";


        return this.itScmStockDao.page(sql, params.toArray(), start, limit);
    }


    //车辆入库后，修改车辆信息的状态为入库

    /**
     * @param carId
     * @throws Exception
     * 修改内容：删除werehouseid和enterdate属性
     * 修改日期：2017、07、13
     */
    private void updateCarStatus(String carId) throws Exception {

        String hql = "update TScmCar set status ='1' where id = :carId";
        Map params = new HashMap();
        // params.put("warehouseId", warehouseId);
        //params.put("enterDate",enterDate);
        params.put("carId", carId);
        this.itScmStockDao.update(hql, params);
    }

    /**
     * 已入库车辆
     *
     * @param data
     * @param start
     * @param limit
     * @param uid
     * @return
     * @throws Exception
     */
    @Override
    public Map newpage(Map data, String status, String start, String limit, String uid,String type) throws Exception {
        Common common = new Common();
        Boolean hasWhere = false;
        StringBuffer sql = new StringBuffer();
        List params = new ArrayList();
        sql.append("select * from ( select p.*,p.car_model model_name,p.configure configure_name,p.car_model_code model_code,tsw.id warehouse_id," +
                  " DATE_FORMAT(tss.enter_date,'%Y-%m-%d') enter_date from T_SCM_CAR p " +
                " right join t_scm_stock tss on p.vin=tss.vin left join t_scm_warehouse tsw on tsw.id=tss.warehouse_id ");
        /*sql.append("select * from ( select p.*,p.car_model model_name,p.configure configure_name from " + tabName1 + " p " +
                " left join "+tabName+ " tss on p.vin=tss.vin ");*/
        //默认只能看自己组织下数据
        String cid = TokenUtil.getCompanyId(uid);
        if(!cid.isEmpty()){
            hasWhere = common.appendWhereIfNeed(sql, hasWhere);
            sql.append(" p.company_id = ? ");
            params.add(cid);
        }
        //入库类型(1采购2已售入库3调拨)
        if (data.get("status") != null && !StringUtils.isEmpty(data.get("status"))) {
            hasWhere = common.appendWhereIfNeed(sql, hasWhere);
            sql.append("  tss.enter_type = ? ");
            params.add(data.get("status"));
        }
        //入库时间起
        if (data.get("enterWarehouseDateBegin") != null && !StringUtils.isEmpty(data.get("enterWarehouseDateBegin"))) {
            hasWhere = common.appendWhereIfNeed(sql, hasWhere);
            sql.append("  DATE_FORMAT(enter_date,'%Y-%m-%d') >= ? ");
            params.add(data.get("enterWarehouseDateBegin"));
        }
        //入库时间止
        if (data.get("enterWarehouseDateEnd") != null && !StringUtils.isEmpty(data.get("enterWarehouseDateEnd"))) {
            hasWhere = common.appendWhereIfNeed(sql, hasWhere);
            sql.append("  DATE_FORMAT(enter_date,'%Y-%m-%d') <= ? ");
            params.add(data.get("enterWarehouseDateEnd"));
        }
        //0采购在途1在库2已售3调拨在途
        if (!status.equals("")) {
            hasWhere = common.appendWhereIfNeed(sql, hasWhere);
            sql.append("  p.status = ? ");
            params.add(status);
        }
        //采购日期起
        if (data.get("purchaseStartDate") != null && !StringUtils.isEmpty(data.get("purchaseStartDate"))) {
            hasWhere = common.appendWhereIfNeed(sql, hasWhere);
            sql.append("  purchase_date >= ? ");
            params.add(data.get("purchaseStartDate"));
        }
        //采购日期到
        if (data.get("purchaseStopDate") != null && !StringUtils.isEmpty(data.get("purchaseStopDate"))) {
            hasWhere = common.appendWhereIfNeed(sql, hasWhere);
            sql.append("  purchase_date <= ? ");
            params.add(data.get("purchaseStopDate"));
        }
        //车系
        if (data.get("carSeriesCode") != null && !StringUtils.isEmpty(data.get("carSeriesCode"))) {
            hasWhere = common.appendWhereIfNeed(sql, hasWhere);
            sql.append("  p.car_series_id = ? ");
            params.add(data.get("carSeriesCode"));
            //车型代码
            if (data.get("carModelCode") != null && !StringUtils.isEmpty(data.get("carModelCode"))) {
                hasWhere = common.appendWhereIfNeed(sql, hasWhere);
                sql.append("  p.car_model_id = ? ");
                params.add(data.get("carModelCode"));
                //车辆配置
                if (data.get("carConfigureCode") != null && !StringUtils.isEmpty(data.get("carConfigureCode"))) {
                    hasWhere = common.appendWhereIfNeed(sql, hasWhere);
                    sql.append("  p.configure_id = ?");
                    params.add(data.get("carConfigureCode"));

                }
            }
        }
        //仓库
        if (data.get("warehouse") != null && !StringUtils.isEmpty(data.get("warehouse"))) {
            hasWhere = common.appendWhereIfNeed(sql, hasWhere);
            sql.append("  tss.warehouse_id = ? ");
            params.add(data.get("warehouse"));
        }
        //vin
        if (data.get("vin") != null && !StringUtils.isEmpty(data.get("vin"))) {
            hasWhere = common.appendWhereIfNeed(sql, hasWhere);
            sql.append("  p.vin like ? ");
            params.add("%" + data.get("vin") + "%");
        }
        //财务状态
        if("1".equals(type)){//暂估入库已入库1
            if (data.get("financeType") != null && "1".equals(data.get("financeType"))) {
                hasWhere = common.appendWhereIfNeed(sql, hasWhere);
                sql.append("  p.finance_type in (2,3) ");

            }
        }else {//车辆入库已入库0
            if (data.get("financeType") != null && "1".equals(data.get("financeType"))) {
                hasWhere = common.appendWhereIfNeed(sql, hasWhere);
                sql.append("  p.finance_type in (1,2,3) ");
            }
        }

        //提单号
        if (data.get("orderNum") != null && !StringUtils.isEmpty(data.get("orderNum"))) {
            hasWhere = common.appendWhereIfNeed(sql, hasWhere);
            sql.append("  p.old_num like ? ");
            params.add("%" + data.get("orderNum") + "%");
        }
        sql.append(" order by date_format(tss.enter_date,'%Y-%m-%d') desc ) as temp ");
        return this.itScmStockDao.page(sql.toString(), params.toArray(), start, limit);

    }

    /**
     * @param data vin数组
     * @return
     * @throws Exception
     * @desc 单车录入盘点结果
     * @author 术洪超
     */

    @Override
    public void updateRight(Map data) throws Exception {

        List<Map> list = (List<Map>) data.get("vins");
        System.out.println(data.get("vins"));
        List<String> vinList = new ArrayList();
        for (Map map : list) {
            vinList.add(map.get("vin").toString());
            System.out.println(map.get("vin"));
        }
        Map param = new HashMap();
        StringBuffer hql = new StringBuffer();
        hql.append("update " + entityName + " set differenceType = '0', differenceReason = '' where  ");
        hql.append(" vin in (:vinList)  ");
        System.out.println(vinList);
        param.put("vinList", vinList);

        this.itScmStockDao.update(hql.toString(), param);

        /*//盘点车辆总数
        List<Map<String,Object>> lists = this.itScmStockDao.list("select count(1) as carCount from t_scm_stock where difference_type is not null");
        this.itScmStockDao.executeSQL("update t_scm_inventory set car_count = ? where id=? ",lists.get(0).get("carCount"),data.get("id"));*/
}


    /**
     * @param data vin数组
     * @return
     * @throws Exception
     * @desc 单车录入盘点结果
     * @author 术洪超
     */

    @Override
    public void updateError(Map data) throws Exception {

        List<Map> list = (List<Map>) data.get("vins");
        System.out.println(data.get("vins"));
        List<String> vinList = new ArrayList();
        for (Map map : list) {
            vinList.add(map.get("vin").toString());
            System.out.println(map.get("vin"));
        }

        Map params = new HashMap();
        StringBuffer hqls = new StringBuffer();
        hqls.append("update " + entityName + " set differenceType = '2' where ");
        hqls.append(" vin in (:vinList)  ");
        params.put("vinList", vinList);
        this.itScmStockDao.update(hqls.toString(), params);

        /*//盘点车辆总数
        List<Map<String,Object>> lists = this.itScmStockDao.list("select count(1) as carCount from t_scm_stock where difference_type is not null");
        this.itScmStockDao.executeSQL("update t_scm_inventory set car_count = ? where id=? ",lists.get(0).get("carCount"),data.get("id"));*/
    }

    /**
     * @param data 保存的参数数组
     * @return
     * @throws Exception
     * @desc 根据vin添加差异原因
     * @author 术洪超
     */
    @Override
    public void saveReason(Map data) throws Exception {

        List<Map> list = (List<Map>) data.get("vins");
        List<String> vinList = new ArrayList();
        for (Map map : list) {
            vinList.add(map.get("vin").toString());
        }

        Map params = new HashMap();
        StringBuffer hql = new StringBuffer();
        hql.append("update " + entityName + " set differenceReason =:differenceReason  where ");
        params.put("differenceReason", data.get("differenceReason"));
        hql.append(" vin in(:vinList) and differenceType != '0' ");
        params.put("vinList", vinList);

        this.itScmStockDao.update(hql.toString(), params);

    }

    private boolean checkCarInStock(String carId)
    {
        try {
            if (this.itScmStockDao.info("select * from T_Scm_Stock where car_id = ?", carId).size()<=0) {
                return false;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return true;
    }
}
